package com.example.tnot.Util.popupwindow;

import android.app.Service;
import android.content.Intent;
import android.graphics.PixelFormat;
import android.os.IBinder;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;

import androidx.localbroadcastmanager.content.LocalBroadcastManager;

import com.example.tnot.R;

public class FloatWindowService extends Service{
    private WindowManager windowManager;
    private View floatView;
    private WindowManager.LayoutParams params;
    ImageView iv_add;
    boolean isVisible = true;
    // 添加Fragment的根视图引用（需要在Fragment中设置）
    private static View fragmentRootView;
    @Override
    public void onCreate() {
        super.onCreate();
        windowManager = (WindowManager) getSystemService(WINDOW_SERVICE);

        LayoutInflater inflater = LayoutInflater.from(this);
        floatView = inflater.inflate(R.layout.float_window, null);
        iv_add = floatView.findViewById(R.id.iv_add);

        params = new WindowManager.LayoutParams(
                WindowManager.LayoutParams.WRAP_CONTENT,
                WindowManager.LayoutParams.WRAP_CONTENT,
                WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY,
                WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
                PixelFormat.TRANSLUCENT);

        // 初始位置
        params.gravity = Gravity.TOP | Gravity.START;
//        距离右边屏幕20dp
        params.x = windowManager.getDefaultDisplay().getWidth() - floatView.getWidth() - 200;
        params.y = windowManager.getDefaultDisplay().getHeight() - floatView.getHeight() - 750;
        windowManager.addView(floatView, params);

//        updatePositionToFragment();
        floatView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 添加调试日志
                android.util.Log.d("FloatWindowService", "悬浮窗被点击");

                Intent clickIntent = new Intent("com.example.tnot.FLOAT_WINDOW_CLICKED");
                Intent Course_intent = new Intent("com.example.tnot.Course.Click.Item");
                Intent Chapter_intent = new Intent("com.example.tnot.Course.chapter");
                LocalBroadcastManager.getInstance(getApplicationContext()).sendBroadcast(clickIntent);
                LocalBroadcastManager.getInstance(getApplicationContext()).sendBroadcast(Course_intent);
                LocalBroadcastManager.getInstance(getApplicationContext()).sendBroadcast(Chapter_intent);

            }
        });
    }

//    /**
//     * 更新悬浮窗位置到Fragment右下角
//     */
//    private void updatePositionToFragment() {
//        if (fragmentRootView != null) {
//            // 获取Fragment在屏幕中的位置
//            int[] location = new int[2];
//            fragmentRootView.getLocationOnScreen(location);
//
//            Rect visibleRect = new Rect();
//            fragmentRootView.getGlobalVisibleRect(visibleRect);
//
//            // 计算Fragment右下角坐标
//            int fragmentRight = visibleRect.right;
//            int fragmentBottom = visibleRect.bottom;
//
//            // 设置悬浮窗位置（距离Fragment右下角有一定边距）
//            int margin = dpToPx(20); // 20dp边距
//            params.x = fragmentRight - floatView.getWidth() - margin;
//            params.y = fragmentBottom - floatView.getHeight() - margin;
//
//            params.gravity = Gravity.TOP | Gravity.START;
//        } else {
//            // 如果没有设置Fragment根视图，使用屏幕右下角作为fallback
//            params.gravity = Gravity.TOP | Gravity.START;
//            params.x = windowManager.getDefaultDisplay().getWidth() - floatView.getWidth() - dpToPx(20);
//            params.y = windowManager.getDefaultDisplay().getHeight() - floatView.getHeight() - dpToPx(100);
//        }
//
//        if (floatView != null && windowManager != null) {
//            windowManager.updateViewLayout(floatView, params);
//        }
//    }
//    /**
//     * 设置Fragment根视图（需要在Fragment中调用）
//     */
//    public static void setFragmentRootView(View rootView) {
//        fragmentRootView = rootView;
//    }

    /**
     * 更新悬浮窗位置（当Fragment滚动时调用）
     */
//    public void updateFloatingWindowPosition() {
//        updatePositionToFragment();
//    }
//
//    private int dpToPx(int dp) {
//        float density = getResources().getDisplayMetrics().density;
//        return Math.round(dp * density);
//    }
//
//

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (floatView != null) {
            windowManager.removeView(floatView);

        }
    }
    public void showFloatingWindow(){
        if (floatView !=null&& !isVisible){
            floatView.setVisibility(View.VISIBLE);
            isVisible = true;
        }
    }
    public void hideFloatingWindow(){
        if (floatView !=null&& isVisible){
            floatView.setVisibility(View.GONE);
            isVisible = false;
        }
    }
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        if (intent != null) {
            String action = intent.getAction();
            if ("SHOW".equals(action)) {
                showFloatingWindow();
            } else if ("HIDE".equals(action)) {
                hideFloatingWindow();
            }
        }
        return super.onStartCommand(intent, flags, startId);
    }



    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }
}